<template>
  <x-page>
    <x-filter @search="handleSearch" @reset="resetSearch">
      <x-filter-item :label="$t('financialSynergy.invoice.invoiceId')">
        <el-input v-model="searchParams.number" :placeholder="'请输入'" clearable maxlength="50"></el-input>
      </x-filter-item>
      <x-filter-item :label="$t('financialSynergy.invoice.supplier')">
        <supplier-select
          ref="supplier-select"
          :value="searchParams.supplierName"
          :placeholder="'请选择供应商'"
          @on-change="handleChangeSupplier"
        >
        </supplier-select>
      </x-filter-item>
      <x-filter-item :label="$t('financialSynergy.invoice.state')">
        <x-select
          :placeholder="$t('common.all')"
          v-model="searchParams.state"
          :options="dictOptions['srm_invoice.state']"
          style="width: 100%"
        ></x-select>
      </x-filter-item>
      <x-filter-item :label="$t('financialSynergy.invoice.ceratTime')">
        <el-date-picker
          v-model="searchParams.createTime"
          type="daterange"
          value-format="yyyy-MM-dd"
          :range-separator="$t('common.to')"
          :start-placeholder="$t('common.startTime')"
          :end-placeholder="$t('common.endTime')"
          clearable
        >
        </el-date-picker>
      </x-filter-item>
    </x-filter>
    <x-data>
      <template #tool>
        <el-row type="flex" class="tools" justify="space-between">
          <el-col :span="20">
            <el-button
              type="primary"
              :icon="buttonIcons('add')"
              @click="handleCreate"
              v-hasPermi="['srm:invoiceNotice:add']"
            >
              {{ $t('common.add') }}</el-button
            >
            <!-- <el-button type="primary" :icon="buttonIcons('send')" @click="handleBatchSend">
              {{ $t('common.send') }}</el-button
            > -->
            <!-- <el-button type="primary" :icon="buttonIcons('export')" @click="handleExport">
              {{ $t('common.export') }}</el-button
            > -->
            <!-- <el-button type="danger" :icon="buttonIcons('delete')" @click="handleBatchDelete">
              {{ $t('common.batchDelete') }}</el-button
            > -->
          </el-col>
          <el-col :span="4" class="tools-config">
            <x-column-config :columns="columns" @updateColumns="updateColumns" @on-refresh="loadData" />
          </el-col>
        </el-row>
      </template>
      <x-table
        ref="tableCom"
        :pagination="pagination"
        :data-source="tableData"
        :loading="loading"
        :row-key="'id'"
        @on-change="handleTableChange"
        @on-selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column :label="$t('common.serialNumber')" :width="55" fixed type="index" />
        <el-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :prop="item.prop"
          :fixed="item.fixed"
          :show-overflow-tooltip="true"
          :width="item.width"
          :min-width="item.minWidth || '-'"
          :label="item.label"
          :sortable="'custom'"
        >
          <template #default="scope">
            <!-- <x-state-cell
              v-if="item.prop === 'state'"
              :stateClass="scope.row[item.prop] === 0 ? 'gray' : scope.row[item.prop] ? 'success' : ''"
              :text="selectDictLabel(dictOptions['srm_invoice.state'], scope.row[item.prop] + '')"
            /> -->
            <span v-if="item.prop === 'state'">
              {{ selectDictLabel(dictOptions['srm_invoice.state'], scope.row[item.prop] + '') }}
            </span>
            <span v-else-if="item.prop === 'payState'">
              {{ selectDictLabel(dictOptions['srm_pay.state'], scope.row[item.prop] + '') }}
            </span>
            <span v-else-if="item.prop === 'invoicingDate'">
              {{ replaceDateTime(scope.row[item.prop]) }}
            </span>
            <span v-else-if="item.prop === 'invoiceType'">
              {{ selectDictLabel(dictOptions['srm_invoice.invoice_type'], scope.row[item.prop]) }}
            </span>
            <span v-else-if="item.prop === 'amount'">
              {{ parseFloat(scope.row[item.prop]).toFixed(2) }}
            </span>
            <span v-else>
              {{ scope.row[item.prop] | emptyVal }}
            </span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" :label="$t('common.opeartion')" :align="'center'" width="160">
          <template #default="scope">
            <more-table-actions
              :action-list="getActions(actions, scope.row)"
              :permis-list="permissionsActions"
              :row="scope.row"
              @onActionClick="handleActions"
            />
          </template>
        </el-table-column>
      </x-table>
    </x-data>
  </x-page>
</template>
<script>
  import {
    buttonIcons,
    PermissionsMixin,
    QueryDictMixin,
    TableListMixin,
    selectDictLabel,
    replaceDateTime
  } from '@package/utils'
  import { columns, actions, conditions } from '../config/invoiceNotice.js'
  import { listUrl, apiDeleteInvoice, apiGetPublishInvoice, apiGetCancelInvoice } from '../api/invoiceNotice.js'

  import SupplierSelect from '@/components/supplier-select/index.vue'
  import { EnumApiCode } from '../../../../../../globalEnum.js'

  export default {
    name: 'InvoiceNotice',
    components: {
      SupplierSelect
    },
    mixins: [TableListMixin, QueryDictMixin, PermissionsMixin],
    data() {
      return {
        columns,
        actions,
        listUrl,
        conditions,
        loading: false,
        searchParams: {
          number: '',
          supplierName: '',
          state: '',
          createTime: ''
        },
        srmDictKeys: ['srm_invoice.invoice_type', 'srm_invoice.state', 'srm_pay.state'],
        dictKeys: []
      }
    },
    computed: {
      getActions() {
        return (actions, { state }) => {
          const btns = actions.map((action) => {
            if (!this.conditions[state].includes(action.key)) {
              action.disabled = true
            } else {
              action.disabled = false
            }
            return action
          })
          return btns
        }
      }
    },
    methods: {
      replaceDateTime,
      buttonIcons,
      selectDictLabel,
      handleSearch(val) {
        const { supplierName, number, state, createTime } = this.searchParams
        this.queryParam = {
          ...val,
          supplierName,
          number,
          state,
          beginTime: createTime ? `${createTime[0]} 00:00:00` : '',
          endTime: createTime ? `${createTime[1]} 23:59:59` : ''
        }
        this.loadData()
      },
      handleChangeSupplier(val) {
        this.searchParams.supplierName = val.fullName
      },
      handleActions({ key, data }) {
        const { id } = data
        switch (key) {
          case 'send':
            this.handleSendInfo(id)
            break
          case 'delete':
            this.handleDeleteInfo(id)
            break
          case 'cancel':
            this.handleCancelInfo(id)
            break
          case 'confirm':
            this.$router.push({
              path: '/financialSynergy/invoiceNoticeConfirm',
              query: {
                id,
                action: 'confirm'
              }
            })
            break
          case 'complte':
            this.$router.push({
              path: '/financialSynergy/invoiceNoticeCollect',
              query: {
                id,
                action: 'complte'
              }
            })
            break
          case 'view':
            this.$router.push({
              path: '/financialSynergy/invoiceNoticeInfo',
              query: {
                id,
                action: 'view'
              }
            })
            break
          case 'edit':
            this.$router.push({
              path: '/financialSynergy/editInvoiceNotice',
              query: {
                id
              }
            })
            break
        }
      },
      // 创建
      handleCreate() {
        this.$router.push({
          name: 'addInvoiceNotice'
        })
      },
      // 批量发送
      handleBatchSend() {
        if (!this.selectionRows.length) {
          this.$message.warning(this.$t('financialSynergy.invoice.sendTips'))
          return
        }
        const ids = this.selectionRows.map((v) => v.id)
        this.handleCancelInfo(ids)
      },
      // 导出
      handleExport() {},
      // 批量删除
      handleBatchDelete() {
        if (!this.selectionRows.length) {
          this.$message.warning(this.$t('financialSynergy.invoice.deleteTips'))
          return
        }
        const ids = this.selectionRows.map((v) => v.id)
        this.handleDeleteInfo(ids)
      },
      handleDeleteInfo(id) {
        this.$confirm(this.$t('financialSynergy.invoice.confirmDelete'), this.$t('common.tip'), {
          confirmButtonText: this.$t('common.sure'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }).then(async () => {
          const { code } = await apiDeleteInvoice(id)
          if (code === EnumApiCode.Success) {
            this.$message.success(this.$t('common.deleteSuccess'))
            this.loadData()
          }
        })
      },
      handleSendInfo(id) {
        this.$confirm(this.$t('financialSynergy.invoice.confirmSend'), this.$t('common.tip'), {
          confirmButtonText: this.$t('common.sure'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }).then(async () => {
          const { code } = await apiGetPublishInvoice(id)
          if (code === EnumApiCode.Success) {
            this.$message.success(this.$t('common.opeartionSuccess'))
            this.loadData()
          }
        })
      },
      async handleCancelInfo(id) {
        this.$confirm(this.$t('financialSynergy.invoice.confirmCacnel'), this.$t('common.tip'), {
          confirmButtonText: this.$t('common.sure'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }).then(async () => {
          const { code } = await apiGetCancelInvoice(id)
          if (code === EnumApiCode.Success) {
            this.$message.success(this.$t('common.opeartionSuccess'))
            this.loadData()
          }
        })
      }
    }
  }
</script>
